<?php

abstract class AModel
{
	protected $table;
	protected $fields = array();
	protected $data = array();
	protected $revision;
	protected $should_revise = false;
	private $id_field = "id";
	private $xml_exceptions;

	protected function invalidArguments($in_obj)
	{ throw new PlatformInvalidModelArgumentsException("Invalid constructor hash provided for ".$in_obj); }

	public function import(&$in_args,$in_automatic=true)
	{
		if ($in_automatic)
			$this->fields = array_keys($in_args);

		$myargs = array();
		foreach ($in_args as $field => $arg)
		{
			$myargs[$field] = stripslashes($arg);
		}
		$this->data = array_merge($this->data,$myargs);
		if(!in_array('id', $this->fields))
		{
			// No id column, look for a probable candidate
			foreach($this->fields as $column)
			{
				if(preg_match('/^.*_id$/', $column))
				{
					$this->setIdField($column);
					break;
				}
			}
		}
		$this->xml_exceptions = array();
	}

	public function get($in_facet)
	{
		return (isset($this->data[$in_facet])) ? $this->data[$in_facet] : null;
	}

	public function set($in_facet,$in_value=null)
	{
		if (is_null($in_value))
			unset($this->data[$in_facet]);
		else
			$this->data[$in_facet] = $in_value;
		return $this->get($in_facet);
	}

	public function setIdField($field)
	{
		$this->id_field = $field;
	}

	public function getIdField()
	{
		return $this->id_field;
	}

	public function getId()
	{
		return $this->get($this->getIdField());
	}

	public function setRevision($in_rev)
	{
		$this->revision = $in_rev;
	}

	public function getRevision()
	{
		return $this->revision;
	}

	public function getFields()
	{
		return $this->fields;
	}

	public function getTable()
	{
		return $this->table;
	}

	public function toString()
	{
		return print_r($this->data,true);
	}

	public function isRevisable($in_set_revisable=null)
	{
		return ((!is_null($in_set_revisable)) ? $this->should_revise = $in_set_revisable : $this->should_revise);
	}

	public function excludeFromXML($exceptions=array())
	{
		$this->xml_exceptions = $exceptions;
	}

	public function asXML($data=NULL, $cdata_handled=false)
	{
		if(is_null($data))
			$data = $this->data;

		$xml = "";
		foreach($data as $key => $value)
		{
			if(!in_array($key, $this->xml_exceptions))
			{
				$key = str_replace(" ", "_", $key);
				if(is_array($value))
				{
					foreach($value as $text)
					{
						$xml = $this->buildXML($xml, $key, $text, $cdata_handled);
					}
				}
				else
				{
					$xml = $this->buildXML($xml, $key, $value, $cdata_handled);
				}
			}
		}
		return $xml;
	}

	private function buildXML($xml, $key, $value, $cdata_handled)
	{
		$xml .= "<$key>";
		if(is_numeric($value))
		{
			$xml .= $value;
		}
		else
		{
			if($cdata_handled)
				$xml .= $value;
			else
				$xml .= "<![CDATA[" . $value . "]]>";
		}
		$xml .= "</$key>\n";
		return $xml;
	}


}

?>
